package net.gazhi.delonix.core.convert;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.Array;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.StringUtils;

/**
 * Object[] 数组编辑器<br>
 * 用于将带英文逗号分隔符的字符串转化成指定的对象数组
 * @author Jeffrey Lin 
 *
 *@see com.maxwellchina.framework.core.web.AbstractAnnotationController#initBinder
 */
public class CustomArrayEditor extends PropertyEditorSupport {
	
	private final ConversionService conversionService;
	private final Class<?> elementType;
	
	public CustomArrayEditor(Class<?> elementType, ConversionService conversionService) {
		this.elementType=elementType;
		this.conversionService=conversionService;
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		if (text == null) {
			setValue(null);
		}
		
		String[] fields = StringUtils.commaDelimitedListToStringArray(text);
		//当 text="" 时，StringUtils.commaDelimitedListToStringArray，会返回长度为0的数组
		//在此处修正为长度为 1 的数组
		if(fields==null || fields.length==0){
			fields=new String[]{""};
		}
		
		Object target = Array.newInstance(elementType, fields.length);
		for (int i = 0; i < fields.length; i++) {
			String sourceElement = fields[i];
			Object targetElement = this.conversionService.convert(sourceElement.trim(), TypeDescriptor.forObject(sourceElement), TypeDescriptor.valueOf(elementType));
			Array.set(target, i, targetElement);
		}
		setValue(target);
	}
}
